<template>
    <div class="forgetContainer">
        <el-card class="forgetCard">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" style="padding-right: 7%;">
                <el-form-item label="邮箱" prop="email">
                    <el-input size="large" v-model="form.email" placeholder="请输入您的邮箱" />
                </el-form-item>

                <el-form-item label="验证码" prop="verificationCode">
                    <el-input size="large" v-model="form.verificationCode" placeholder="请输入验证码" />
                    <el-button @click="sendVerificationCode" size="small" type="primary" :loading="sendingCode">
                        获取验证码
                    </el-button>
                </el-form-item>

                <el-form-item label="新密码" prop="newPassword">
                    <el-input size="large" type="password" v-model="form.newPassword" placeholder="请输入新密码" />
                </el-form-item>

                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input size="large" type="password" v-model="form.confirmPassword" placeholder="请确认新密码" />
                </el-form-item>

                <el-form-item>
                    <el-button size="large" type="primary" @click="handleResetPassword"
                        :loading="loading">重置密码</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElCard, FormItemRule, ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

import { forgetPassword, getEamilCode } from '@/api';
import { Arrayable } from 'element-plus/es/utils';

export default defineComponent({
    name: 'ForgotPassword',
    components: {
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
        ElCard
    },
    setup() {
        const router = useRouter();  // 获取路由实例
        const route = useRoute();    // 获取当前路由信息
        const formRef = ref(null);
        const form = ref({
            email: '',
            verificationCode: '',
            newPassword: '',
            confirmPassword: ''
        });

        const loading = ref(false); // 控制按钮的加载状态
        const sendingCode = ref(false); // 控制获取验证码按钮的加载状态

        // 验证新密码和确认密码是否匹配
        const checkPasswordMatch = (rule: any, value: string, callback: Function) => {
            if (value !== form.value.newPassword) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        };
        // 表单验证规则
        const rules: Partial<Record<string, Arrayable<FormItemRule>>> = {
            email: [
                {
                    required: true,
                    message: '请输入邮箱',
                    trigger: 'blur'
                },
                {
                    type: 'email',
                    message: '请输入有效的邮箱地址',
                    trigger: ['blur', 'change']
                }
            ],
            verificationCode: [
                {
                    required: true,
                    message: '请输入验证码',
                    trigger: 'blur'
                }
            ],
            newPassword: [
                {
                    required: true,
                    message: '请输入新密码',
                    trigger: 'blur'
                }
            ],
            confirmPassword: [
                {
                    required: true,
                    message: '请确认新密码',
                    trigger: 'blur'
                },
                {
                    validator: checkPasswordMatch,
                    trigger: 'blur'
                }
            ]
        };

        // 发送验证码（模拟）
        const sendVerificationCode = () => {
            sendingCode.value = true;
            const email = form.value.email
            if(email){
                getEamilCode(email).then(res=>{
                    ElMessage.success("验证码已发送到您的邮箱")
                    sendingCode.value = false;
                })
            }else{
                ElMessage.error("请填写正确的email！")
            }
        };

        // 重置密码的处理函数
        const handleResetPassword = async () => {
            await formRef.value?.validate().then(() => {
                loading.value = true;
                forgetPassword(getRequestBody()).then(res => {
                    loading.value = false;
                    if (res['code'] === 200) {
                        ElMessage.success('密码重置成功！')
                        router.push({ 'name': 'login' })
                    } else {
                        ElMessage.error(res['msg'])
                    }
                    // 在这里可以进行实际的重置密码 API 调用

                    console.log(res);

                })

            }).catch(() => {
                console.log('表单验证失败');
            });
        };

        // 获取请求体
        const getRequestBody = () => {
            const username = route.query.username;
            let request = {
                confirmPassword: "", email: "", password: "", username: "", captcha: ""
            }

            request.confirmPassword = form.value.confirmPassword
            request.email = form.value.email
            request.username = username.toString()
            request.password = form.value.newPassword
            request.captcha = form.value.verificationCode
            return request
        }
        return {
            form,
            loading,
            sendingCode,
            rules,
            formRef,
            sendVerificationCode,
            handleResetPassword
        };
    }
});
</script>

<style scoped>
.forgetContainer {
    width: 100%;
    height: 100%;
    background: url('../../assets/image/login.png') 50% no-repeat;
    background-size: 100% 100%;
    position: relative;
}

.forgetCard {
    padding: 1.5%;
    width: 30%;
    position: absolute;
    right: 8%;
    top: 25%;
}

.el-form-item {
    margin-bottom: 20px;
}
</style>